package archimede;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import net.miginfocom.swing.MigLayout;

import org.apache.commons.io.FileUtils;

public class Download implements Runnable {

  private StartingWindow st;
  private String author;
  private String nameProject;
  private Integer countRtd;
  private String password;
  private String username;
  private Integer type;
  private Integer risposta;

  public Download(StartingWindow st, String author, String nameproject,
      String progetto, Integer countRtd, String password, String username,
      Integer risposta, Integer type) {
    this.st = st;
    this.author = author;
    this.nameProject = nameproject;
    this.countRtd = countRtd;
    this.password = password;
    this.username = username;
    this.type = type;
    this.risposta = risposta;
  }

  @Override
  public void run() {
    if (risposta == 0) {
      // caricamento file
      FTPClient client = new FTPClient();

      try {
        // connessione
        client.setPassive(true);
        client.connect("eureka.archimedegroup.eu");
        // login
        client.login(username, password);
        //

        client.changeDirectory("ProgettoArchimede");

        if (type == st.AMMINISTRATORE)
          client.changeDirectory("AMMINISTRATORE");
        else if (type == st.SILVER) {
          client.changeDirectory("SILVER");
          client.changeDirectory(author);
        }
        client.changeDirectory(nameProject);
        client.changeDirectory("eureka");

        // trova la home
        Properties pc = System.getProperties();
        String homePath = pc.getProperty("user.home");
        String directoryProject = homePath + pc.getProperty("file.separator")
            + "ArchimedeSuper" + pc.getProperty("file.separator") + nameProject;

        // se c'è scovrascivo il progetto
        File dirtmp = new File(directoryProject);
        if (dirtmp.exists()) {
          FileUtils.forceDelete(dirtmp);
        }
        dirtmp.mkdir();

        // download
        // eureka
        FTPFile[] list;
        MyTransferListener transfer = new MyTransferListener();
        try {
          list = client.list();
          transfer.setLength(list.length);

          transfer.setStatus("EUREKA  ");
          for (int i = 0; i < list.length; i++) {
            // System.out.println(list[i].getName());
            client.download(list[i].getName(),
                new File(directoryProject + pc.getProperty("file.separator")
                    + list[i].getName()), transfer);

          }
          // mi sposto in extra
          transfer.allegati();

          client.changeDirectoryUp();
          client.changeDirectory("extra");
          dirtmp = new File(directoryProject + pc.getProperty("file.separator")
              + "extra");
          dirtmp.mkdir();
          list = client.list();
          // extra

          for (int i = 0; i < list.length; i++) {
            // System.out.println(list[i].getName());
            if (list[i].getType() == FTPFile.TYPE_FILE)
              client.download(
                  list[i].getName(),
                  new File(dirtmp + pc.getProperty("file.separator")
                      + list[i].getName()), transfer);
            else {
              client.changeDirectory(list[i].getName());
              File newDirtmp = new File(dirtmp
                  + pc.getProperty("file.separator") + list[i].getName());
              newDirtmp.mkdir();
              FTPFile[] subList = client.list();
              for (int k = 0; k < subList.length; k++) {
                // System.out.println(list[i].getName());
                if (subList[k].getType() == FTPFile.TYPE_FILE)
                  client.download(subList[k].getName(),
                      new File(newDirtmp + pc.getProperty("file.separator")
                          + subList[k].getName()), transfer);
                else {
                  client.changeDirectory(subList[k].getName());
                  File newDirtmp2 = new File(newDirtmp
                      + pc.getProperty("file.separator") + subList[k].getName());
                  newDirtmp2.mkdir();
                  FTPFile[] subList2 = client.list();
                  for (int k2 = 0; k2 < subList2.length; k2++) {
                    // System.out.println(list[i].getName());
                    if (subList2[k2].getType() == FTPFile.TYPE_FILE)
                      client.download(subList2[k2].getName(), new File(
                          newDirtmp2 + pc.getProperty("file.separator")
                              + subList2[k2].getName()), transfer);
                  }
                  client.changeDirectoryUp();
                }
              }
              client.changeDirectoryUp();
            }
          }
          // op.showMessageDialog(null, "DOWNLOAD TERMINATO");
        } catch (Throwable e2) {
          JOptionPane
              .showMessageDialog(null,
                  "Errore nel download, premere nuovamente download e inserire credenziali");
        }
        transfer.hideWindow();
        // client.logout();
        client.disconnect(true);
        // file di salvataggio
        String filePath = directoryProject + pc.getProperty("file.separator")
            + countRtd + ".txt";
        // prendo i dati dal file .txt
        File toScan = new File(filePath);
        try {
          Scanner c = new Scanner(toScan);
          int index = 0;
          String done = "";
          while (c.hasNextLine()) {
            String tmp = c.nextLine();
            if (tmp.contains("@@")) {
              st.setField(index, done);
              done = "";
              index++;

            } else
              done = done + "\n" + tmp;
          }
          c.close();

        } catch (FileNotFoundException e1) {

          e1.printStackTrace();
        }

      } catch (IllegalStateException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      } catch (IOException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      } catch (FTPIllegalReplyException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      } catch (FTPException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      }

      st.getWIndow().setTitle("EUREKA - ARCHIMEDE" + " ~ Progetto " + countRtd);

    } else if (risposta == 1) {
      // caricamento file
      FTPClient client = new FTPClient();
      try {

        // connessione
        client.setPassive(true);
        client.connect("eureka.archimedegroup.eu");
        // login
        client.login(username, password);
        //
        client.changeDirectory("ProgettoArchimede");

        if (type == st.AMMINISTRATORE)
          client.changeDirectory("AMMINISTRATORE");
        else if (type == st.SILVER) {
          client.changeDirectory("SILVER");
          client.changeDirectory(author);
        }
        client.changeDirectory(nameProject);
        client.changeDirectory("eureka");

        // trova la home
        Properties pc = System.getProperties();
        String homePath = pc.getProperty("user.home");
        String directoryProject = homePath + pc.getProperty("file.separator")
            + "ArchimedeSuper" + pc.getProperty("file.separator") + nameProject;

        // se c'è scovrascivo il progetto
        File dirtmp = new File(directoryProject);
        if (dirtmp.exists()) {
          FileUtils.forceDelete(dirtmp);
        }
        dirtmp.mkdir();

        // download
        MyTransferListener transfer = new MyTransferListener();

        try {
          // eureka
          FTPFile[] list = client.list();
          transfer.setLength(list.length);
          for (int i = 0; i < list.length; i++) {
            // System.out.println(list[i].getName());
            client.download(list[i].getName(),
                new File(directoryProject + pc.getProperty("file.separator")
                    + list[i].getName()), transfer);

          }
          // op.showMessageDialog(null, "DOWNLOAD TERMINATO");
        } catch (Throwable e2) {
          JOptionPane
              .showMessageDialog(null,
                  "Errore nel download, premere nuovamente download e inserire credenziali");
          e2.printStackTrace();
        }
        transfer.hideWindow();

        // client.logout();
        client.disconnect(true);
        // file di salvataggio
        String filePath = directoryProject + pc.getProperty("file.separator")
            + countRtd + ".txt";
        // prendo i dati dal file .txt
        File toScan = new File(filePath);

        try {
          Scanner c = new Scanner(toScan);
          int index = 0;
          String done = "";
          while (c.hasNextLine()) {
            String tmp = c.nextLine();
            if (tmp.contains("@@")) {
              st.setField(index, done);
              done = "";
              index++;

            } else
              done = done + "\n" + tmp;
          }
          c.close();

        } catch (FileNotFoundException e1) {

          e1.printStackTrace();
        }

      } catch (IllegalStateException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      } catch (IOException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      } catch (FTPIllegalReplyException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      } catch (FTPException e2) {
        JOptionPane
            .showMessageDialog(null,
                "Errore nel download, premere nuovamente download e inserire credenziali");
        e2.printStackTrace();
      }
      st.getWIndow().setTitle("EUREKA - ARCHIMEDE" + " ~ Progetto " + countRtd);
    }

  }

  public class MyTransferListener extends JFrame implements
      FTPDataTransferListener {

    private JProgressBar bar;
    private Integer max;
    private Integer transferred = 0;
    private String directory = "";

    public MyTransferListener() {
      super("Download");
      try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      } catch (UnsupportedLookAndFeelException localUnsupportedLookAndFeelException) {
      } catch (ClassNotFoundException localClassNotFoundException) {
      } catch (InstantiationException localInstantiationException) {
      } catch (IllegalAccessException localIllegalAccessException) {
      }
      bar = new JProgressBar(0, 100);
      bar.setPreferredSize(new Dimension(200, 40));
      bar.setStringPainted(true);
      setLayout(new MigLayout());
      add(new JLabel("Attendere download in corso"), "cell 0 0");

      add(bar, "cell 0 1");
      pack();
      setLocation(st.getWidth() / 2 - getWidth() / 2, st.getHeight() / 2
          - getHeight() / 2);
      setVisible(true);
    }

    public void setLength(Integer max) {
      this.max = max;

    }

    public void started() {
      // Trasferimento avviato
    }

    public void setStatus(String status) {
      directory = status;
    }

    public void hideWindow() {
      setVisible(false);
    }

    public void allegati() {
      directory = "Allegati";
      transferred = -1;
      remove(bar);
      bar = new JProgressBar();
      bar.setIndeterminate(true);
      bar.setPreferredSize(new Dimension(200, 40));
      bar.setStringPainted(true);
      bar.setString(directory);
      add(bar, "cell 0 1");
      paintAll(getGraphics());
    }

    public void transferred(int length) {
    }

    public void completed() {
      if (transferred == -1) {
        bar.setString(directory);
      } else {
        transferred++;
        bar.setValue((int) ((transferred * 100) / max));
        bar.setString(directory + (int) ((transferred * 100) / max) + "%");
      }

    }

    public void aborted() {
      // Trasferimento annullato
    }

    public void failed() {
      // Trasferimento fallito
    }

  }
}
